package z_mxsTest.testCleanMutiLangCommonWithList;

import javax.swing.*;
import java.io.File;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 文件匹配器 - 按规则匹配目标文件
 */
public class FileMatcher {
    //private final CommentCleanerApplication mainApp;
    private final LogUtils logUtils;

    public FileMatcher(CommentCleanerApplication mainApp, LogUtils logUtils) {
        //this.mainApp = mainApp;
        this.logUtils = logUtils;
    }

    public void matchFiles(File rootDir, List<String> rules, List<File> resultFiles, JTextArea displayArea) {
        resultFiles.clear();
        StringBuilder displayText = new StringBuilder();

        if (rules.isEmpty()) {
            displayArea.setText("⚠️ 无有效规则可匹配");
            return;
        }

        for (String rule : rules) {
            String regex = convertRuleToRegex(rule);
            scanDirectory(rootDir, rootDir, regex, resultFiles);
        }

        if (resultFiles.isEmpty()) {
            displayArea.setText("⚠️ 未匹配到任何文件");
        } else {
            for (int i = 0; i < resultFiles.size(); i++) {
                String relativePath = getRelativePath(rootDir, resultFiles.get(i));
                displayText.append(i + 1).append(". ").append(relativePath).append("\n");
            }
            displayText.append("\n✅ 共匹配到 ").append(resultFiles.size()).append(" 个文件");
            displayArea.setText(displayText.toString());
        }
        logUtils.log("文件匹配完成，找到" + resultFiles.size() + "个目标文件");
    }

    private String convertRuleToRegex(String rule) {
        return rule.replace("\\", "/")
                   .replace(".", "\\.")
                   .replace("*", "[^/]*")
                   .replace("**", ".*")
                   .replace("?", ".");
    }

    private void scanDirectory(File rootDir, File currentDir, String regex, List<File> resultFiles) {
        if (!currentDir.isDirectory()) return;

        File[] files = currentDir.listFiles();
        if (files == null) return;

        for (File file : files) {
            if (file.isDirectory()) {
                scanDirectory(rootDir, file, regex, resultFiles);
            } else {
                String relativePath = getRelativePath(rootDir, file).replace("\\", "/");
                if (Pattern.matches(regex, relativePath)) {
                    resultFiles.add(file);
                }
            }
        }
    }

    private String getRelativePath(File rootDir, File file) {
        try {
            return rootDir.toPath().relativize(file.toPath()).toString();
        } catch (Exception e) {
            return file.getAbsolutePath();
        }
    }
}